﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MindmeisterAPI
{
    class Request
    {
        protected Dictionary<string, string> _parameters;


        protected string _method;

        public Request(string pApiKey, string pMethod)
        {
            _parameters = new Dictionary<string, string>();
            _parameters.Add("api_key", pApiKey);
            _parameters.Add("method", pMethod);
        }

        public void AddParameter(string pKey, string pValue)
        {
            _parameters.Add(pKey, pValue);
        }

        public string GetSignature(string pSharedKey)
        {
            StringBuilder res = new StringBuilder();
            res.Append(pSharedKey);

            foreach (KeyValuePair<string, string> item in _parameters.OrderBy(key => key.Key))
            {
                res.Append(item.Key);
                res.Append(item.Value);
            }

            return ComputeMD5(res.ToString());
        }

        public string GetParamsUrl()
        {
            StringBuilder res = new StringBuilder();
            string returnValue;

            foreach (KeyValuePair<string, string> item in _parameters.OrderBy(key => key.Key))
            {
                res.Append(item.Key);
                res.Append("=");
                res.Append(item.Value);
                res.Append("&");
            }

            returnValue = (res.Length > 0) ? res.Remove(res.Length - 1, 1).ToString() : "";

            return returnValue;

        }




        private string ComputeMD5(string pString)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(pString);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString();
        }
    }
}
